<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .box {
        width: 100px;
        height: 100px;
        background-color: bisque;
        position: fixed;
        cursor: pointer;
        box-sizing: content-box;
        border: 2px solid transparent;
        transition: 100ms;
      }
      .box:hover {
        border-color: rebeccapurple;
      }

      .box.active {
        border-color: rebeccapurple;
        font-size: 2rem;
      }
    </style>
  </head>
  <body>
    <div class="box" data-mouse>box1</div>
    <div class="box" data-mouse>box2</div>
    <div class="box" data-mouse>box3</div>
    <script>
      let activeBox = null;
      document.onclick = function (e) {
        const target = e.target;
        const mouse = target.dataset.mouse;
        if (mouse === undefined) {
          return;
        }
        // 清除所有的激活状态
        document
          .querySelectorAll("[data-mouse]")
          .forEach((el) => el.classList.remove("active"));
        // 添加当前激活类
        target.classList.add("active");

        activeBox = target;
      };

      window.onkeydown = function (e) {
        if (activeBox === null) {
          alert("请选中一个老鼠");
          return;
        }
        const speed = 30;
        const key = e.key;
        const { top, left, width, height } = activeBox.getBoundingClientRect();
        if (key === "ArrowUp") {
          if (top < 0) {
            activeBox.style.top = 0 + "px";
          } else {
            activeBox.style.top = top - speed + "px";
          }
        }
        if (key === "ArrowDown") {
          if (top > window.innerHeight - height) {
            activeBox.style.top = window.innerHeight - height + "px";
          } else {
            activeBox.style.top = top + speed + "px";
          }
        }
        if (key === "ArrowLeft") {
          if (left < 0) {
            activeBox.style.left = 0 + "px";
          } else {
            activeBox.style.left = left - speed + "px";
          }
        }
        if (key === "ArrowRight") {
          if (left > window.innerWidth - width) {
            activeBox.style.left = window.innerWidth - width + "px";
          } else {
            activeBox.style.left = left + speed + "px";
          }
        }
      };
    </script>
  </body>
</html>
